<?php
/**
 * LilAttachment Behavior for CakePHP 2.0
 * 
 * @copyright     Copyright 2008, Miha Nahtigal (http://www.nahtigal.com)
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 * 
 * 
 * This LilAttachment behavior for CakePHP auto manages attachments for
 * specified model.
 * 
 */
class LilAttachmentBehavior extends ModelBehavior {
/**
 * An array with default settings
 */
	private $__defaultSettings = array(
	);
/**
 * An array of settings set by the $actsAs property
 */
    private $_settings = array();

/**
 * Instantiates the behavior and sets the magic methods
 * 
 * @param object $model The Model object
 * @param array $settings Array of scope properties
 */
	public function setup($model, $config = array()) {
		$settings = array_merge($this->__defaultSettings, $config);
		$this->_settings[$model->alias] = $settings;
		
		$bind_name = Inflector::pluralize($model->name) . 'Attachment';
		$model->bindModel(array('hasMany' => array($bind_name => array(
			'className' => 'Lil.LilAttachment',
			'foreignKey' => 'foreign_id',
			'conditions' => array($bind_name . '.model' => $model->name),
			'order'      => $bind_name . '.created',
			'dependent'  => true
		))), false);
		
		$model->resetAssociations();
		$model->$bind_name->bindModel(array('belongsTo' => array($model->name => array(
			'counterCache' => !isset($settings['counterCache']) || $settings['counterCache'],
			'foreignKey' => 'foreign_id',
			'conditions' => array($bind_name . '.model' => $model->name),
		))), false);

		$model->$bind_name->Behaviors->attach('Lil.LilUpload', array_merge(
			$model->$bind_name->uploadDefaults,		
			$this->_settings[$model->alias]
		));
	}

}